﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using System.Collections.Concurrent;
using System.Collections;
using System.Drawing;
using System.Dynamic;

using System.Threading;
using System.Net;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Windows.Forms;
using System.Windows.Media.Imaging; //
using App2Wpf.Models;
using System.Windows.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using System.ComponentModel;
using System.Windows.Threading;
using App2Wpf.Views;


namespace App2Wpf
{
    public class ViewerBase : ObservableObject
    {
        public WPFWindow remoteWin;   // 设置静态字段 会只有一个窗口 不适用
        public bool IsStop;
        public bool IsShowControlWindow;
        public BitmapSource _cardFrame;

        public BitmapSource m_bitmapSource
        {
            get => _cardFrame;
            set
            {
                SetProperty(ref _cardFrame, value);
            }
        }

        public CardModel _VirtualDeskForm;
        public CardModel VirtualDeskForm
        {
            get => _VirtualDeskForm;
            set
            {
                SetProperty(ref _VirtualDeskForm, value);
            }
        }

        public string ServerAddress { get; set; } = "127.0.0.1";
        public IPAddress Server { get; set; }

        public nameip wininfo { get; set; }

        public int ServerPort { get; set; } = 8021;

        public bool UseTLS1_3 { get; set; }

        public bool DisableVerbosity { get; set; }

        public SecureString SecurePassword { get; set; }

        public String Password { get; set; }

        public ClipboardMode Clipboard { get; set; } = ClipboardMode.Both;

        public int ImageCompressionQuality { get; set; } = 75;

        public bool Resize { get; set; }

        public int ResizeRatio { get; set; } = 90;

        public bool AlwaysOnTop { get; set; }

        public PacketSize packetSize { get; set; } = PacketSize.Size9216;

        public BlockSize blockSize { get; set; } = BlockSize.Size64;

        public bool LogonUI { get; set; }

        public List<PSCustomObject> runspaces { get; set; }

        public clientViewerSession session { get; set; }

        


        public Hashtable virtualDesktopSyncHash { get; set; }
        

        public ConcurrentDictionary<string, ClientIO> virtualDesktopSyncDic { get; set; } = new ConcurrentDictionary<string, ClientIO>();



        public ClientIO outputEventIO { get; set; }

        public Hashtable outputEventSyncHash { get; set; }
        public ConcurrentDictionary<string, ClientIO> outputEventSyncDic { get; set; } = new ConcurrentDictionary<string, ClientIO>();



        public Hashtable HostSyncHash { get; set; } = new Hashtable();


        





        public ViewerBase(IPAddress Server, nameip wininfo)
        {
            this.Server = Server;
            this.wininfo = wininfo;

            string host = "";
            string ClipboardText = "";
            HostSyncHash.Add("host", host);
            HostSyncHash.Add("ClipboardText", ClipboardText);

            HostSyncHash = Hashtable.Synchronized(HostSyncHash);
        }

         virtual public void init(IPAddress server)
        {

            //Session successfully established, start streaming...

            //Create WinForms Environment...
            VirtualDeskForm = new CardModel();
            

            //(VirtualDeskForm.pictureBox1 as Control).MouseDown += logic_MouseDown;
            //(VirtualDeskForm.pictureBox1 as Control).MouseUp += logic_MouseUp;
            //(VirtualDeskForm.pictureBox1 as Control).MouseMove += logic_MouseMove;
            //(VirtualDeskForm.pictureBox1 as Control).MouseWheel += logic_MouseWheel;

            //(VirtualDeskForm.pictureBox1 as Control).DoubleClick += logic_DoubleClick;
            //(VirtualDeskForm.pictureBox1 as Control).KeyPress += logic_KeyPress;
            //(VirtualDeskForm.pictureBox1 as Control).KeyUp += logic_KeyUp;
            //(VirtualDeskForm.pictureBox1 as Control).KeyDown += logic_KeyDown;
            //(VirtualDeskForm.pictureBox1 as Control).Leave += logic_Leave;

            //this.virtualDesktopDic = new Dictionary<int, remoteWindow>();
            //virtualDesktopDic.Add(0, VirtualDeskForm);

            var tempHashtable = new Hashtable();
            tempHashtable.Add("VirtualDesktop", VirtualDeskForm);
            var virtualDesktopSyncHash = Hashtable.Synchronized(tempHashtable);

            VirtualDeskForm.cardTitle = string.Format(
                "{0} {1}[{2}x{3}]:{4}/{5}-{6}",
                wininfo.name,
                wininfo.ip,
                0,
                0,
                //session.ServerInformation.Version,
                0,
                0,
                0);
            //加载窗口后刷新 20230520
            //Session successfully established, start streaming...
            this.session = new clientViewerSession();
            this.session.Server = server;
            Task.Run(() =>
            {
                session.OpenSession();
                session.ConnectDesktopWorker();
                session.ConnectEventsWorker();

                var outputEvent = new Hashtable();
                outputEvent.Add("Writer", session.ClientEvents.Writer);
                outputEventSyncHash = Hashtable.Synchronized(outputEvent);
                outputEventSyncDic.GetOrAdd("outputEvent", session.ClientEvents);

                VirtualDeskForm.cardTitle = string.Format(
                    "{0} {1}[{2}x{3}]:{4}/{5}-{6}",
                    wininfo.name,
                    wininfo.ip,
                    session.ViewerConfiguration.RemoteDesktopWidth,
                    session.ViewerConfiguration.RemoteDesktopHeight,
                    //session.ServerInformation.Version,
                    session.ServerInformation.Username,
                    session.ServerInformation.MachineName,
                    session.ServerInformation.WindowsVersion);

                //test 20221107
                //VirtualDeskForm.ClientSize = new Size(
                //    session.ViewerConfiguration.VirtualDesktopWidth,
                //    session.ViewerConfiguration.VirtualDesktopHeight);

                //  Create a thread-safe hashtable to send events to remote server.

                //Hashtable outputable = new Hashtable();
                //outputable.Add("Writer", session.ClientEvents.Writer);
                //var outputEventSyncHash = Hashtable.Synchronized(outputable);

                if (!session.ServerInformation.ViewOnly)
                {

                }

                VirtualDesktopUpdater(session.ClientDesktop,
                virtualDesktopSyncHash,
                session.ViewerConfiguration,
                session.PacketSize);

            });

            //补充绘制 本地鼠标图像，更新剪切板
            IngressEventUpdater(session.ClientEvents, virtualDesktopSyncHash, Clipboard);


            //samll window  not control
            //EgressEventUpdater(virtualDesktopSyncHash, Clipboard);



        }


        virtual public void VirtualDesktopUpdater(ClientIO Client,
                Hashtable virtualDesktopSyncHash,
                clientViewerConfiguration ViewerConfiguration,
                PacketSize packetSize)
        {
            byte[] mstruct = new byte[sizeof(Int32) * 3];
            System.IO.MemoryStream mstream = new System.IO.MemoryStream();

            Point destPoint = new Point(0, 0);
            Bitmap scene = new Bitmap(ViewerConfiguration.RemoteDesktopWidth, ViewerConfiguration.RemoteDesktopHeight);

            Graphics sceneGraphics = Graphics.FromImage(scene);
            sceneGraphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;

            //while (!virtualDesktopDic[0].Form.Visible)
            //{
            //    Thread.Sleep(100);

            //}

            //Tiny hack to correctly bring to front window, this is the most effective technique so far.
            //VirtualDesktopSyncHash.VirtualDesktop.Form.TopMost = true;
            //VirtualDesktopSyncHash.VirtualDesktop.Form.TopMost = false;

            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        Client.SSLStream.Read(mstruct, 0, mstruct.Length);

                        long totalBufferSize = System.Runtime.InteropServices.Marshal.ReadInt32(mstruct, 0x0);

                        destPoint.X = System.Runtime.InteropServices.Marshal.ReadInt32(mstruct, 0x4);
                        destPoint.Y = System.Runtime.InteropServices.Marshal.ReadInt32(mstruct, 0x8);

                        mstream.SetLength(totalBufferSize);

                        mstream.Position = 0;

                        while (mstream.Position != mstream.Length)
                        {
                            long bufferSize = mstream.Length - mstream.Position;
                            if (bufferSize > (long)packetSize)
                            {
                                bufferSize = (long)packetSize;
                                int mbufferSize = (int)packetSize;

                            }
                            //读数据数据流到内存中
                            mstream.Write(  Client.BinaryReader.ReadBytes((int)bufferSize),
                                0, 
                                (int)bufferSize );
                        }
                        if (mstream.Length == 0)
                        {
                            continue;
                        }

                        ///# Next Iterations
                        sceneGraphics.DrawImage(
                                System.Drawing.Image.FromStream(mstream),
                                destPoint
                            );


                        m_bitmapSource = clientFunc.BitmapToBitmapImage(scene);
                        //Trace.WriteLine($"X:{destPoint.X}，Y:{destPoint.Y}，");
                        //Trace.Flush();

                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine(DateTime.Now);
                        Trace.WriteLine($"{destPoint.X}，{destPoint.Y},");
                        Trace.WriteLine(e);
                        Trace.Flush();
                        Trace.Close();
                        clientFunc.Showlog(e.Message);
                        continue;
                        //throw;
                    }

                    //finally
                    //{
                    //    if (scene != null)
                    //    {
                    //        scene.Dispose();
                    //    }

                    //    if (sceneGraphics != null)
                    //    {
                    //        sceneGraphics.Dispose();
                    //    }

                    //    if (mstream != null)
                    //    {
                    //        mstream.Close();
                    //    }
                    //}
                }
            }


              //VirtualDesktopSyncHash.VirtualDesktop.Close();
              
              );
            //DesktopUpdater.Start();



        }

        public void IngressEventUpdater(ClientIO Client, Hashtable virtualDesktopSyncHash, ClipboardMode Clipboard)
        {
           Task.Run(() =>
            {
                while (true)
                {
                    if (IsStop) return;
                    try
                    {
                        var jsonEvent = Client.Reader.ReadLine();
                    }
                    catch (InvalidOperationException error2)
                    {

                        clientFunc.ShowErrorlog(error2.Message);
                        return;
                    }
                    catch (Exception error)
                    {

                        clientFunc.ShowErrorlog(error.Message);
                        continue;
                    }
                    
                    try
                    {
                        var jsonEvent = Client.Reader.ReadLine();
                        SEvent jsonobj = (SEvent)JsonConvert.DeserializeObject(jsonEvent, typeof(SEvent));
                        if ((int)jsonobj.Id != 3) continue;
                        switch ((InputEvent)jsonobj.Id)
                        {
                            case InputEvent.MouseCursorUpdated:
                                {
                                    if (jsonobj.Cursore != null)
                                    {
                                        Cursor newcur = Cursors.Arrow;
                                        switch ((CursorType)jsonobj.Cursore)
                                        {
                                            case CursorType.IDC_APPSTARTING:
                                                newcur = Cursors.AppStarting;
                                                break;
                                            case CursorType.IDC_ARROW:
                                                newcur = Cursors.Arrow;
                                                break;
                                            case CursorType.IDC_CROSS:
                                                newcur = Cursors.Cross;
                                                break;
                                            case CursorType.IDC_HAND:
                                                newcur = Cursors.Hand;
                                                break;
                                            case CursorType.IDC_HELP:
                                                newcur = Cursors.Help;
                                                break;
                                            case CursorType.IDC_IBEAM:
                                                newcur = Cursors.IBeam;
                                                break;
                                            //case CursorType.IDC_ICON:
                                            //    newcur = Cursors.No;
                                            //    break;
                                            case CursorType.IDC_NO:
                                                newcur = Cursors.No;
                                                break;
                                            case CursorType.IDC_SIZE:
                                                newcur = Cursors.SizeAll;
                                                break;
                                            case CursorType.IDC_SIZEALL:
                                                newcur = Cursors.SizeAll;
                                                break;
                                            case CursorType.IDC_SIZENESW:
                                                newcur = Cursors.SizeNESW;
                                                break;
                                            case CursorType.IDC_SIZENS:
                                                newcur = Cursors.SizeNS;
                                                break;
                                            case CursorType.IDC_SIZENWSE:
                                                newcur = Cursors.SizeNWSE;
                                                break;
                                            case CursorType.IDC_SIZEWE:
                                                newcur = Cursors.SizeWE;
                                                break;
                                            case CursorType.IDC_UPARROW:
                                                newcur = Cursors.UpArrow;
                                                break;
                                            case CursorType.IDC_WAIT:
                                                newcur = Cursors.WaitCursor;
                                                break;
                                            default:
                                                break;
                                        }

                                        //VirtualDeskForm.pictureBox1.Cursor = newcur;
                                    }
                                    else { continue; }


                                }
                                break;

                            case InputEvent.ClipboardUpdated:
                                {
                                    if (Clipboard == ClipboardMode.Disabled
                                        || Clipboard == ClipboardMode.Send)
                                    {
                                        continue;

                                    }

                                    HostSyncHash.Clear();
                                    HostSyncHash.Add("ClipboardText", jsonobj.Text);
                                    clientFunc.Showlog(jsonobj.Text);
                                    //本地剪切板
                                    System.Windows.Clipboard.SetText(jsonobj.Text);  //wpf


                                }

                                break;
                            case InputEvent.DesktopActive:
                                break;
                            case InputEvent.DesktopInactive:
                                break;
                            default:
                                break;
                        }
                    }
                    catch (Exception error2)
                    {

                        clientFunc.ShowErrorlog(error2.Message);
                        continue;
                    }


                }
            }
            );

        }

        //定时检测剪切板，输出给远程剪切板
        public void EgressEventUpdater(Hashtable virtualDesktopSyncHash, ClipboardMode Clipboard)
        {
            Task EgressEventUpdater = new Task(() =>
            {

                Stopwatch stopWatch = Stopwatch.StartNew();
                while (true)
                {
                    if (IsStop) return;
                    if (stopWatch.ElapsedMilliseconds >= 1000)
                    {
                        try
                        {
                            bool eventTriggered = false;

                            if (!eventTriggered)
                            {
                                object dd = new { };
                                if (!sendEvent(OutputEvent.KeepAlive, dd))
                                {
                                    break;
                                }

                            }
                        }
                        //catch (Exception)
                        //{

                        //    throw;
                        //}
                        finally
                        {
                            stopWatch.Restart();
                        }
                    }
                }
            });
            EgressEventUpdater.Start();
        }



        public void VirtualDeskFormIO_closing(object sender, FormClosingEventArgs e)
        {
            this.session.CloseSession();
        }

        public PSCustomObject MouseEvent(int X, int Y, MouseState type, string button = "")
        {
            var CustomObject = new PSCustomObject();
            CustomObject.Id = (int)OutputEvent.MouseClickMove;
            CustomObject.X = X;
            CustomObject.Y = Y;
            CustomObject.Button = button;
            CustomObject.Type = type;
            return CustomObject;
        }

        public PSCustomObject KeyboardEvent(string Keys = "")
        {
            var CustomObject = new PSCustomObject();
            CustomObject.Id = (int)OutputEvent.Keyboard;

            CustomObject.Keys = Keys;
            return CustomObject;
        }

        public bool sendEvent(OutputEvent oee, object data)
        {
            try
            {
                if (data == null)
                {
                    data = new { Id = oee };
                }
                else
                {
                }
                data = new { Id = oee };
                //session.ClientEvents.WriteJson(data);
                outputEventSyncDic["outputEvent"].WriteJson(data);

                return true;
            }
            catch (Exception)
            {
                return false;
                //throw;
            }

        }

        public void SendVirtualMouse(int X, int Y, MouseState type, string button = "")
        {
            if (session.ViewerConfiguration.RequireResize)
            {
                X = (int)(X * session.ViewerConfiguration.ScreenX_Ratio);
                Y = (int)(Y * session.ViewerConfiguration.ScreenY_Ratio);
            }

            X += session.ViewerConfiguration.ScreenX_Delta;
            Y += session.ViewerConfiguration.ScreenY_Delta;

            //PSCustomObject temp = MouseEvent(X, Y, type, button);
            object temp = new
            {
                Id = (int)OutputEvent.MouseClickMove,  ///simulate mouse move and clicks //copy control 1129
                X = X,
                Y = Y,
                Type = (int)type,
                Button = button,
            };
            try
            {
                //outputEventSyncHash.WriteJson(temp);
                //session.ClientEvents.WriteJson(temp);
                outputEventSyncDic["outputEvent"].WriteJson(temp);
                //clientFunc.Showlog($"{X},{Y}");

            }
            catch (Exception)
            {

                //throw;
            }
        }

        public void SendVirtualKeyboard(string Keys = "")
        {
            object temp = new { Id = OutputEvent.Keyboard, Keys = Keys };

            try
            {
                //session.ClientEvents.WriteJson(temp);
                outputEventSyncDic["outputEvent"].WriteJson(temp);

            }
            catch (Exception)
            {

                //throw;
            }
        }

        public void logic_MouseDown(object sender, MouseEventArgs e)
        {
            SendVirtualMouse(e.X, e.Y, MouseState.Down, e.Button.ToString()); // "Left"
        }

        public void logic_MouseUp(object sender, MouseEventArgs e)
        {
            SendVirtualMouse(e.X, e.Y, MouseState.Up, e.Button.ToString());

        }

        public void logic_MouseMove(object sender, MouseEventArgs e)
        {

            SendVirtualMouse(e.X, e.Y, MouseState.Move, e.Button.ToString());

        }

        public void logic_MouseWheel(object sender, MouseEventArgs e)
        {
            object temp = new
            {
                Id = OutputEvent.MouseWheel,
                Delta = e.Delta
            };
            try
            {
                //session.ClientEvents.WriteJson(temp);
                outputEventSyncDic["outputEvent"].WriteJson(temp);

            }
            catch (Exception)
            {

                //throw;
            }

        }

        public void WPF_logic_MouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {
            object temp = new
            {
                Id = OutputEvent.MouseWheel,
                Delta = e.Delta
            };
            try
            {
                //session.ClientEvents.WriteJson(temp);
                outputEventSyncDic["outputEvent"].WriteJson(temp);

            }
            catch (Exception)
            {

                //throw;
            }

        }

        public void logic_DoubleClick(object sender, EventArgs e)
        {
        }

        public void logic_KeyPress(object sender, KeyPressEventArgs e)
        {
            string keychar = "";
            switch (e.KeyChar.ToString())
            {
                case "{":
                    keychar = "{{}";
                    break;
                case "}":
                    keychar = "{}}";
                    break;
                case "+":
                    keychar = "{+}";
                    break;
                case "^":
                    keychar = "{^}";
                    break;
                case "%":
                    keychar = "{%}";
                    break;
                case "~":
                    keychar = "{~}";
                    break;
                case "(":
                    keychar = "{(}";
                    break;
                case ")":
                    keychar = "{)}";
                    break;

                case "[":
                    keychar = "{[}";
                    break;
                case "]":
                    keychar = "{]}";
                    break;

                default:
                    keychar = e.KeyChar.ToString();
                    break;
            }

            SendVirtualKeyboard(keychar);


        }

        public void logic_KeyUp(object sender, KeyEventArgs e)
        {

        }

        public void logic_KeyDown(object sender, KeyEventArgs e)
        {
            string res = "";
            if (Map.funcKeymap.ContainsKey(e.KeyValue))
            {
                res = Map.funcKeymap[e.KeyValue];
            }

            if (!string.IsNullOrEmpty(res))
            {
                SendVirtualKeyboard(res);
            }
        }

        /// <summary>
        /// 远端接收方式 [System.Windows.Forms.SendKeys]::SendWait($aEvent.Keys)
        /// </summary>
        public void WPF_logic_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {

            string res = "";
            switch (e.Key) 
            {
                case System.Windows.Input.Key.Enter:   //System.Windows.Input.Key.Return:
                    res = "{ENTER}";
                    break;
                case System.Windows.Input.Key.Back:
                    res = "{BACKSPACE}";
                    break;
                case System.Windows.Input.Key.Space:  /////
                    res = " ";
                    break;
                case System.Windows.Input.Key.Tab:
                    res = "{TAB}";
                    break;
                case System.Windows.Input.Key.CapsLock:
                    res = "{CAPSLOCK}";
                    break;
                case System.Windows.Input.Key.Insert:
                    res = "{INSERT}";
                    break;
                case System.Windows.Input.Key.PageUp:
                    res = "{PGUP}";
                    break;
                case System.Windows.Input.Key.PageDown:
                    res = "{PGDW}";
                    break;
                case System.Windows.Input.Key.LWin:
                case System.Windows.Input.Key.RWin:
                    res = "^{ESC}";
                    break;
                case System.Windows.Input.Key.Escape:
                    res = "{ESC}";
                    break;

                /////////////////////////////////////////////
                ///
                //case System.Windows.Input.Key.OemMinus:
                //    res = "{-}";
                //    break;
                //case System.Windows.Input.Key.OemOpenBrackets:
                //    res = "{[}";
                //    break;
                //case System.Windows.Input.Key.OemCloseBrackets:
                //    res = "{]}";
                //    break;
                //case System.Windows.Input.Key.OemPipe:  ////   "|"
                //    res = "{\\}";  //tong 145
                //    break;
                //case System.Windows.Input.Key.OemSemicolon:
                //    res = "{;}";
                //    break;
                //case System.Windows.Input.Key.OemQuotes:
                //    res = "{'}";
                //    break;

                //case System.Windows.Input.Key.OemComma:
                //    res = "{,}";
                //    break;
                //case System.Windows.Input.Key.OemPeriod:
                //    res = "{.}";
                //    break;
                //case System.Windows.Input.Key.OemQuestion:
                //    res = "{/}";
                //    break;
                //case System.Windows.Input.Key.OemTilde:
                //    res = "{`}";
                //    break;


                ///////////////////////////////////////////////
                //case System.Windows.Input.Key.LeftCtrl:
                //case System.Windows.Input.Key.RightCtrl:
                //    res = "{^}";               //////////////      CONTROL ==> ^
                //    break;
                //case System.Windows.Input.Key.LeftAlt:
                //case System.Windows.Input.Key.RightAlt:
                //    res = "{%}";                  /////////////     ALT  ==>  %
                //    break;
                //case System.Windows.Input.Key.LeftShift:
                //case System.Windows.Input.Key.RightShift:
                //    res = "{+}";                 ////////////       SHIFT ==> +
                //    break;

                default:
                    if (Map.WPF_FuncKeyList.Contains((int)e.Key))
                    {
                        res = string.Format("{0}{2}{1}", "{", "}", e.Key.ToString().ToUpper());
                    }
                    break;
            }
            if (!string.IsNullOrEmpty(res))
            {
                SendVirtualKeyboard(res);
                return;
            }

            //Keys formKeyIntput = (System.Windows.Forms.Keys)System.Windows.Input.KeyInterop.VirtualKeyFromKey(e.Key);
            //string SendKeyStr = ((char)formKeyIntput).ToString();
            //string keychar = "";
            //switch (SendKeyStr)   //toString名称，  
            //{
            //    case "{":
            //        keychar = "{{}";
            //        break;
            //    case "}":
            //        keychar = "{}}";
            //        break;
            //    case "+":
            //        keychar = "{+}";
            //        break;
            //    case "^":
            //        keychar = "{^}";
            //        break;
            //    case "%":
            //        keychar = "{%}";
            //        break;
            //    case "~":
            //        keychar = "{~}";
            //        break;
            //    case "(":
            //        keychar = "{(}";
            //        break;
            //    case ")":
            //        keychar = "{)}";
            //        break;

            //    case "[":
            //        keychar = "{[}";
            //        break;
            //    case "]":
            //        keychar = "{]}";
            //        break;

            //    default:
            //        keychar = ((char)formKeyIntput).ToString();
            //        break;
            //}
            //res = keychar;
            //if (!string.IsNullOrEmpty(res))
            //{
            //    SendVirtualKeyboard(res);
            //    return;
            //}



        }

        public void logic_Leave(object sender, EventArgs e)
        {

        }


        //public void FormAddShown(System.Windows.Forms.Form Form1)
        //{
        //    //Center Virtual Desktop Form
        //    VirtualDeskForm.Location = new Point(
        //                   (clientFunc.GetLocalScreenWidth() - VirtualDeskForm.Width) / 2,
        //                   (clientFunc.GetLocalScreenHeight() - VirtualDeskForm.Height) / 2
        //               );

        //    VirtualDeskForm.TopMost = AlwaysOnTop;
        //}

        //public void logic_OpenNewWindow(object sender, EventArgs e)
        //{
        //    if (sender == null) { return; };
        //    ToolStripMenuItem sendered = (ToolStripMenuItem)sender;
        //    if (sendered.Text.StartsWith("OPEN"))
        //    {
        //        ViewerControl sessionControlViewer = new ViewerControl(this.Server, this.wininfo);
        //        sessionControlViewer.VirtualDeskForm.Show();

        //    }
        //    if (sendered.Text.StartsWith("XWindow"))
        //    {
        //        cmdWindow cWin = new cmdWindow();
        //        cWin.textBox1.Text = this.Server.ToString();
        //        cWin.Server = this.Server;
        //        cWin.Show();
        //    }
        //}











    }
}
